package com.example.administrator.myview.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidadvance.topsnackbar.TSnackbar;
import com.example.administrator.myview.MainActivity;
import com.example.administrator.myview.R;

import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EncodingUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import static android.content.Context.MODE_PRIVATE;
import static android.content.Context.NOTIFICATION_SERVICE;

/**
 * 常用工具函数
 * @author 马振雷
 *
 */
public class MyUtils {



    /**
     * 从内置卡/data/data/<应用程序名>/files读数据
     * @param context	调用窗体句柄
     * @param fileName	文件名
     * @return			true：成功；false：失败；
     */
    public static String readFile(Context context, String fileName) {
        String res="";

        try{
            FileInputStream fin = context.openFileInput(fileName);
            int length = fin.available();
            byte[] buffer = new byte[length];
            fin.read(buffer);
            res = EncodingUtils.getString(buffer, "UTF-8");
            fin.close();
        } catch(IOException e){
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 写数据到内置卡/data/data/<应用程序名>/files
     * @param context	调用窗体句柄
     * @param fileName	文件名
     * @param message	文件内容
     * @return			true：成功；false：失败；
     */
    public static boolean writeFile(Context context, String fileName, String message) {
        boolean ret = true;

        try {
            FileOutputStream fout = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            byte[] bytes = message.getBytes();
            fout.write(bytes);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
            ret = false;
        }
        return ret;
    }

    /**
     * 从SD卡上读数据
     * @param fileName	要读入的文件名
     * @return			文件内容
     */
    public static String readCardFile(String fileName) {
        String res="";

        fileName = Environment.getExternalStorageDirectory()+fileName;	//添加SD卡目录
        File file = new File(fileName);
        if (!file.exists()) {
            return res;
        }
        try{
            FileInputStream fin = new FileInputStream(fileName);
            int length = fin.available();
            byte[] buffer = new byte[length];
            fin.read(buffer);
            res = EncodingUtils.getString(buffer, "UTF-8");
            fin.close();
        } catch(IOException e){
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 写数据到SD卡上
     * @param fileName	文件名
     * @param message	要写入的数据
     * @return			true：成功；false：是否；
     */
    public static boolean writeCardFile(String fileName, String message) {
        boolean ret = true;

        try {
            File dir = new File(Environment.getExternalStorageDirectory(), fileName);
            String path = dir.getParent();
            File dir2 = new File(path);
            if(!dir2.exists()) dir2.mkdirs();	//没有目录就创建
            fileName = Environment.getExternalStorageDirectory()+"//"+fileName;	//添加SD卡目录
            FileOutputStream fout = new FileOutputStream(fileName);
            byte[] bytes = message.getBytes();
            fout.write(bytes);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
            ret = false;
        }
        return ret;
    }

    /** 获取不带扩展名的文件名*/
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    /**
     * 监测网络是否连接
     * @param context	调用窗体句柄
     * @return			true：已连接；false：未连接；
     */
    public static boolean isConnected(Context context){
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        return networkInfo != null && networkInfo.isConnected();
    }

    /**
     * 解压数GZIP据流
     * @param inStream		输入字符流
     * @param charsetName	字符集
     * @return				转换后的字符串
     * @throws Exception    异常
     */
    public static String readDataForZgip(InputStream inStream, String charsetName) throws Exception {
        GZIPInputStream gzipStream = new GZIPInputStream(inStream);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer =new  byte[1024];
        int len;

        while ((len = gzipStream.read(buffer))!=-1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        gzipStream.close();
        inStream.close();
        return new String(data, charsetName);
    }

    /**
     * 判断是否安装目标应用
     * @param packageName	要判断的软件包名
     * @return				true：已安装；false：未安装；
     */
    public static boolean isInstallByread(String packageName) {
        return new File("//data//data//" + packageName).exists();
    }

    /**
     * ListView自适应高度
     * @param listView	要自适应高度的ListView
     */
    public static void setListViewHeight(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 字符串中判断是否都是字母
     * @param str	要判断的字符串
     * @return		true：是；false：不是
     */
    public static boolean StringIsLetter(String str) {
        boolean bFind = true;

        for (int i=0; i<str.length(); i++) {
            char   c   =   str.charAt(i);
            if (!(c>='a'&&c<='z')||(c>='A'&&c<='Z')) {
                bFind = false;
                break;
            }
        }
        return bFind;
    }

    /**
     * 字符串中判断是否都是数字
     * @param str	要判断的字符串
     * @return		true：是；false：不是
     */
    public static boolean StringIsNumber(String str, int len) {
        if (str.length()!=len) return false;
        boolean bFind = true;

        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                bFind = false;
                break;
            }
        }
        return bFind;
    }

    /**
     * 判断字符串中含有汉字
     * @param str	要判断的字符串
     * @return		true：有；false：无
     */
    public static boolean StringHaveChinese(String str) {
        boolean bFind = false;
        char[] cTemp = str.toCharArray();

        for (int i = 0; i < str.length(); i++) {
            Character.UnicodeBlock ub = Character.UnicodeBlock.of(cTemp[i]);
            if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
                bFind = true;
                break;
            }
        }
        return bFind;
    }

    /**
     * MD5加密，32位
     * @param str	要编码的字符串
     * @return		返回MD5
     */
    public static String MD5(String str) {
        MessageDigest md5;

        try {
            md5 = MessageDigest.getInstance("MD5");
        }catch(Exception e) {
            e.printStackTrace();
            return "";
        }

        char[] charArray = str.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for(int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte)charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);

        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 字符串转换为整型
     * @param str	要转换的字符串
     * @return		转换后的整数
     */
    public static int StringToInt(String str) {
        int result = 0;
        if (str.length()>0) {
            try {
                result = Integer.parseInt(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 字符串转换为浮点数
     * @param str	要转换的字符串
     * @return		转换后的浮点数
     */
    public static double StringToFloat(String str) {
        double result = 0;
        if (str.length()>0) {
            try {
                result = Double.parseDouble(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 字符串转换成金额
     * @param sMoney 要转换的字符串
     * @return 返回四舍五入的金额
     */
    public static double StringToMoney(String sMoney) {
        return StringToFloat(String.format("%.2f", StringToFloat(sMoney)));
    }

    /**
     * 浮点数转换成金额（2位小数）
     * @param dMoney 要转换的浮点是规格的金额
     * @return 返回四舍五入的金额
     */
    public static double FloatToMoney(double dMoney) {
        return StringToFloat(String.format("%.2f", dMoney));
    }

    /**
     * 显示提示信息（只显示1个，覆盖显示）
     * @param toast		显示内容
     * @param context	调用窗体
     */
    public static void showToast(final Context context, final String toast) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }).start();
    }

    /**
     * 显示提示信息（只显示1个，覆盖显示）
     * @param toast		显示内容
     * @param context	调用窗体
     */
    public static void showToast(final Context context, final String toast, final int duration) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(context, toast, duration).show();
                Looper.loop();
            }
        }).start();
    }

    /**
     * 代码暂停
     * @param time	暂停的毫秒数
     */
    public static void delay(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 字符串倒序输出
     * @param str	输入的字符串
     * @return		输出倒序好的字符串
     */
    public static String reverseString(String str) {
        String str2 = "";
        for (int i = str.length() - 1; i > -1; i--) {
            str2 += String.valueOf(str.charAt(i));
        }

        return str2;
    }

    /**
     * 字符串 to 粘贴板
     * @param context	调用窗句柄
     * @param str  		要复制的字符串
     */
    public static void StringToClipboard(Context context, String str)
    {
        ClipboardManager myClipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        myClipboard.setPrimaryClip(ClipData.newPlainText("text", str));
    }

    /**
     * 判断手机号是否合法
     */
    public static boolean isMobilePhone(String mobile) {
        Pattern p = Pattern.compile("^(1)\\d{10}$");
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /**
     * 判断邮箱是否合法
     */
    public static boolean isEmail(String email){
        if (null==email || "".equals(email)) return false;
        Pattern p =  Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 延时
     * @param time	延时的时长（毫秒）
     */
    public static void delay(long time) {
        try {
            Thread.sleep(time);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //尝试打开wifi
    @SuppressLint("MissingPermission")//权限忽略
    private static boolean tryOpenMAC(WifiManager manager) {
        boolean softOpenWifi = false;
        int state = manager.getWifiState();
        if (state != WifiManager.WIFI_STATE_ENABLED && state != WifiManager.WIFI_STATE_ENABLING)
        {
            manager.setWifiEnabled(true);
            softOpenWifi = true;
        }
        return softOpenWifi;
    }

    //尝试关闭MAC
    @SuppressLint("MissingPermission")
    private static void tryCloseMAC(WifiManager manager) {
        manager.setWifiEnabled(false);
    }

    //尝试获取MAC地址
    private static String tryGetMAC(WifiManager manager) {
        WifiInfo wifiInfo = manager.getConnectionInfo();

        if (wifiInfo == null || wifiInfo.getMacAddress() == null)
        {
            return null;
        }
        return wifiInfo.getMacAddress().replaceAll(":", "").trim().toUpperCase();
    }

    /**
     * 获取机器Wifi的Mac地址
     */
    public static String getMacFromDevice(Context context) {
        WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        String mac = tryGetMAC(wifiManager);
        if(mac != null)
        {
            return mac;
        }

        //获取失败，尝试打开wifi获取
        boolean isOkWifi = tryOpenMAC(wifiManager);
        for(int index=0;index<50;index++)
        {
            //如果第一次没有成功，第二次做200毫秒的延迟。
            if(index!=0)
            {
                try
                {
                    Thread.sleep(200);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            mac = tryGetMAC(wifiManager);
            if(mac != null)
            {
                break;
            }
        }

        //尝试关闭wifi
        if(isOkWifi)
        {
            tryCloseMAC(wifiManager);
        }
        return mac;
    }

    /**
     * 判断app是否在后台
     */
    public static boolean isBackground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     *  这个包名的程序是否在运行
     *  @param context 	：上下文
     *  @return 		：必须加载的权限 <uses-permission android:name="android.permission.GET_TASKS">
     */
    public static boolean isRunningApp(Context context) {
        boolean isAppRunning = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        for (RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(context.getPackageName()) || info.baseActivity.getPackageName().equals(context.getPackageName())) {
                isAppRunning = true;
                break;
            }
        }
        return isAppRunning;
    }

    //缩放图片  调整图片转向 - 通过文件
    public static Bitmap scaleImageFromFile(String filePath , int quality, int maxSize) {
        try {
            //获取系统图片旋转方向
            ExifInterface exifInterface = new ExifInterface(filePath);
            int result = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
            int rotate = 0;
            switch(result) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotate = 90;
                    break;

                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotate = 180;
                    break;

                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotate = 270;
                    break;

                default:
                    break;
            }

            //调整图片尺寸
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options);
            options.inSampleSize = computeSampleSize(options, -1, maxSize*maxSize);
            options.inJustDecodeBounds = false;
            Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
            if (bmp != null) {
                //根据上面配置信息，生成新位图
                bmp = scaleImageFromBitmap(bmp, quality, rotate);
            }
            return bmp ;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    //计算图片压缩值-方法1
    private static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;

        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    //计算图片压缩值-方法2
    private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    //缩放图片 - 通过位图
    private static Bitmap scaleImageFromBitmap(Bitmap bmp , int quality, int rotate) {
        //获取图片大小
        int outWidth = bmp.getWidth();
        int outHeight = bmp.getHeight();

        //处理图片图片
        Bitmap bm;
        if(rotate>0){
            Matrix matrix = new Matrix();
            matrix.setRotate(rotate);
            bm = Bitmap.createBitmap(bmp,0,0,outWidth,outHeight,matrix, true);
        }else{
            bm = Bitmap.createScaledBitmap(bmp,outWidth, outHeight,true);
        }
        if (bm != bmp) {	//图片地址不一样就释放内存
            bmp.recycle();
        }

        if (bm != null) {
            //压缩图片
            ByteArrayOutputStream baos = null ;
            try{
                baos = new ByteArrayOutputStream();
                bm.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                try {
                    if(baos != null)
                        baos.close() ;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bm ;
    }

    //位图转换为BASE64字符串
    public static String BitmapToString(Bitmap bitmap) {
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
        byte [] b=baos.toByteArray();
        String temp=null;
        try{
            System.gc();
            temp= Base64.encodeToString(b, Base64.DEFAULT);
        }catch(Exception e){
            e.printStackTrace();
        }catch(OutOfMemoryError e){
            baos=new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,50, baos);
            b=baos.toByteArray();
            temp= Base64.encodeToString(b, Base64.DEFAULT);
            Log.e("6618", "Out of memory error catched");
        }
        return temp;
    }

    //或者系统状态栏高度
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    //小写转换成字符串（去掉后面的0）
    public static String doubleToStringNoZero(double d) {
        int i;
        String s= String.format("%f", d);//将浮点数转为字符串

        for( i=s.length()-1;i>=0;i-- ) {//从串尾向前检查，遇到非0数据结束循环
            if ( s.charAt(i)=='.' ) //遇到小数点结束，说明是个整数
                break;
            if ( s.charAt(i) != '0' ) {//遇到小数中有非0值，结束
                i++;
                break;
            }
        }
        return s.substring(0,i); //返回处理后的子串
    }

    /**
     * 显示提示信息
     */
    public static void toast(Activity activity, String content) {
        Toast.makeText(activity, content, Toast.LENGTH_SHORT).show();
    }

    /**
     * 另一种 橙色背景 白色字体 用于警告信息提示
     */
    public static void snackBar(View view, String content) {
        TSnackbar snackBar = TSnackbar
                .make(view, content, TSnackbar.LENGTH_SHORT);
        View snackBarView = snackBar.getView();
        ViewGroup.LayoutParams linearParams = snackBarView.getLayoutParams(); //取控件View当前的布局参数
        linearParams.height = 250;// 控件的高设成100
        snackBarView.setLayoutParams(linearParams); //使设置好的布局参数应用到控件</pre>
        //snackBarView.setBackgroundColor(Color.parseColor("#FF8200"));
        //snackBarView.setBackgroundResource(R.drawable.shape_border_orange);//设置背景框
        TextView textView=(TextView) snackBarView.findViewById(R.id.snackbar_text);
        textView.setTextColor(Color.WHITE);
        textView.setTextSize(16);
        textView.setMaxLines(1);
        textView.setEllipsize(TextUtils.TruncateAt.END);//末尾省略号
        snackBar.show();
    }

    /**
     * activity跳转（这里为了简化使用时的代码）
     */
    public static void startActivity(Activity activity, Class<?> cls) {
        activity.startActivity(new Intent(activity, cls));
    }

    //窗体启动（带参数）
    public static void start_activity(Activity activity, Class<?> cls,
                                      BasicNameValuePair... name) {
        Intent intent = new Intent();
        intent.setClass(activity, cls);
        for (BasicNameValuePair aName : name) {
            intent.putExtra(aName.getName(), aName.getValue());
        }
        activity.startActivity(intent);
    }

    //窗体启动返回原窗体（带参数）
    public static void start_activityForResult(Activity activity, Class<?> cls, int requestCode,
                                               BasicNameValuePair... name) {
        Intent intent = new Intent();
        intent.setClass(activity, cls);
        for (BasicNameValuePair aName : name) {
            intent.putExtra(aName.getName(), aName.getValue());
        }
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 判断wifi是否连接
     */
    public static boolean isWifiConnect(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 调起系统发短信功能
     */
    public static void sendSMS(Context activity, String phoneNum, String message) {
        Uri uri = Uri.parse("smsto:" + phoneNum);
        Intent intentSMS = new Intent(Intent.ACTION_SENDTO, uri);
        intentSMS.putExtra("sms_body", message);
        activity.startActivity(intentSMS);
    }

    /**
     * 调起系统打电话功能 需要添加权限 <uses-permission
     * android:name="android.permission.CALL_PHONE"/>
     */
    @SuppressLint("MissingPermission")
    public static void callPhone(Context activity, String phoneNum) {
        Uri uri = Uri.parse("tel:" + phoneNum);
        Intent intentTel = new Intent(Intent.ACTION_CALL, uri);
        activity.startActivity(intentTel);
    }

    /**
     * 调用系统打拨号界面
     */
    public static void DialPhone(Context activity, String phoneNum) {
        Uri uri = Uri.parse("tel:" + phoneNum);
        Intent intentDal = new Intent(Intent.ACTION_DIAL, uri);
        activity.startActivity(intentDal);
    }

    /**
     * 调起系统浏览器打开网页
     */
    public static void openWeb(Context activity, String url) {
        Uri uri = Uri.parse(url);
        Intent it = new Intent(Intent.ACTION_VIEW, uri);
        activity.startActivity(it);
    }

    //从文件中读取位图数据
    public static Bitmap getSmallBitmap(File file , int quality, int outWidth, int outHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getPath(), options);
        options.inSampleSize = calculateInSampleSize(options, outWidth, outHeight);
        options.inJustDecodeBounds = false;
        Bitmap bm = BitmapFactory.decodeFile(file.getPath(), options);
        if(bm == null){
            return  null;
        }

        FileOutputStream fos = null ;
        try{
            fos =  new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, quality, fos);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                if(fos != null)
                    fos.close() ;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bm ;
    }

    //处理位图大小
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height  / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
        }

        return inSampleSize;
    }

    /**
     * 根据手机分辨率从dp转成px
     */
    public static int dip2px(Context context, double dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 检查编辑框为空
     */
    public static boolean checkEditIsEmpty(Activity activity, EditText et,
                                           String str) {
        if (("").equals(et.getText().toString().trim())) {
            toast(activity, str);
            return true;
        }
        return false;
    }

    /**
     * 全角转半角
     * 解决android文本未满一行就换行问题
     */
    public static String QtoB(String input) {
        char c[] = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == '\u3000') {
                c[i] = ' ';
            } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
                c[i] = (char) (c[i] - 65248);
            }
        }
        return new String(c);
    }

    /**
     * 半角转为全角
     */
    public static String toDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    /**
     * 判断String值是否为纯数字包括
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }

    /**
     * 验证邮箱地址
     */
    public static boolean isEmailAddr(String emailNum) {

        String check = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(emailNum);
        return matcher.matches();
    }
    /**
     * 是否包含中文
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]+");
        Matcher m = p.matcher(str);
        return m.find();
    }

    //判断是否电话号码
    public static boolean isTelNum(String str) {
        Pattern p = Pattern.compile("[0-9 \\-]+");
        Matcher m = p.matcher(str);
        return m.matches()&&str.length()==11;
    }

    /**
     * 字符串末尾特殊处理
     * str    要处理的字符串
     */
    public static String strEndProcess(String str){
        if (!MyUtils.isMobilePhone(str)) {
            return str;
        }
        StringBuilder sb=new StringBuilder();
        sb.append(str.substring(0, 3));
        for(int i=0;i<str.length()-6;i++){
            sb.append("*");
        }
        sb.append(str.substring(str.length()-3, str.length()));
        return sb.toString();
    }

    /**
     * 将Bitmap解析成字节数组
     */
    public static byte[] readBitmap(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] data = baos.toByteArray();
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * View 平移
     */
    public static void moveFrontBg(View v, int startX, int toX, int startY, int toY) {
        TranslateAnimation anim = new TranslateAnimation(startX, toX, startY, toY);
        anim.setDuration(200);
        anim.setFillAfter(true);
        v.startAnimation(anim);
    }

    // 获取 androidmainfest.xml 文件配置 的ApiKey
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return apiKey;
    }

    //获取线性布局高度
    public static void setLinearLayoutHeight(LinearLayout layout) {
        if (layout == null ||layout.getChildCount()==0) {
            return;
        }
        int totalHeight = 0;

        for (int i = 0; i < layout.getChildCount(); i++) {
            View child = layout.getChildAt(i);
            layout.measure(0, 0);
            totalHeight += child.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = layout.getLayoutParams();
        params.height = totalHeight;
        layout.setLayoutParams(params);
    }

    //获取屏幕高度
    public static int getWindowFrameHeight(Context context){
        Rect fram = new Rect();
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(fram);
        return  fram.height();
    }

    //获取屏幕高度
    public static int getWindowFrameWidth(Context context){
        Rect fram = new Rect();
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(fram);
        return  fram.width();
    }

    //保存字符串到本地文件
    public static void saveFile(String sSaveString, String FileName){
        File fileSave = new File(FileName);
        try {
            if(!fileSave.exists()){
                File dir = new File(fileSave.getParent());
                dir.mkdirs();	//没有目录就创建
                fileSave.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(FileName);
            out.write(sSaveString.getBytes());
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //检测url有效性
    public static boolean checkURL(String url) {
        boolean value = false;
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            int code = conn.getResponseCode();
            value = code == 200;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * str-> date
     */
    public static Date str2Date(String str, String format) {
        Date date = null;
        if (!TextUtils.isEmpty(str)) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            try {
                date = sdf.parse(str);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return date;
    }


    /**
     * 获取软件版本号
     * @param context	窗体句柄
     * @return		版本号（字符串）
     */
    public static String getVersionName(Context context)
    {
        String versionName = "1.0";
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获取软件build号
     * @param context	窗体句柄
     * @return			版本号（数字）
     */
    public static int getVersionCode(Context context)
    {
        int versionCode = 1;
        try {
            versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    /**
     * 清理保存的Cookies数据
     * @param context	应用句柄
     */
    public static void clearCookies(Context context) {
        // Edge case: an illegal state exception is thrown if an instance of
        // CookieSyncManager has not be created.  CookieSyncManager is normally
        // created by a WebKit view, but this might happen if you start the
        // app, restore saved state, and click logout before running a UI
        // dialog in a WebView -- in which case the app crashes
        CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }

    /**
     * 本地存储Cookie
     * @param
     */

    @SuppressLint("ApplySharedPref")
    public static void saveCookies(Context context) {
//		new Thread(networkTask).start();
        CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        String cookies = cookieManager.getCookie("服务器主地址");
        String cookieHost = cookieManager.getCookie("存cookie的地址");
        SharedPreferences preferences = context.getSharedPreferences("cookies", MODE_PRIVATE);
        preferences.edit().putString("cookies",cookieHost).commit();
    }

    /**
     * 给WebView同步Cookie
     *
     * @param context 上下文
     */
    public static void syncCookie(Context context) {
        String url = "服务器存cookie的地址";
        SharedPreferences sharedPreferences = context.getSharedPreferences("cookies", MODE_PRIVATE);
        if(!TextUtils.isEmpty(sharedPreferences.getString("cookies", ""))) {
            String[] cookies = sharedPreferences.getString("cookies", "").split(";");
            CookieManager cookieManager = CookieManager.getInstance();
            for (int i = 0; i < cookies.length ; i++) {
                cookieManager.setCookie(url, cookies[i]);
            }
        }
    }

    /**
     * 通知栏 单聊消息显示在通知栏
     */
    public static void showIntentActivityNotify(String who, String what, Context context, int drawable){
        NotificationCompat.Builder mBuilder;
        NotificationManager mNotificationManager;
        mNotificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(context.getApplicationContext());
        mBuilder.setContentTitle("测试标题")
                .setContentText("测试内容")
                // .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL))
//              .setNumber(number)//显示数量
                .setTicker("测试通知来啦")//通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示
                .setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
//              .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                .setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
//              .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合：
                //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
                .setSmallIcon(drawable);//这个是图片

        // Notification.FLAG_ONGOING_EVENT --设置常驻
        // Flag;Notification.FLAG_AUTO_CANCEL 通知栏上点击此通知后自动清除此通知
        //  notification.flags = Notification.FLAG_AUTO_CANCEL;//在通知栏上点击此通知后自动清除此通知
        mBuilder.setAutoCancel(true)//点击后让通知将消失
                .setContentTitle(who)
                .setContentText(what)
                .setWhen(System.currentTimeMillis())
                .setTicker("您有未读消息");
        //点击的意图ACTION是跳转到Intent 跳转到单聊界面
        Intent resultIntent = new Intent(context, MainActivity.class);
        resultIntent.putExtra("hisId",who);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), 0,resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        if (mNotificationManager != null) {
            mNotificationManager.notify(0, mBuilder.build());
        }
    }

    /**
     * 在onDestroy方法里执行
     * 解决InputMethodManager内存泄露现象 输入法引起的
     */
    private static void fixInputMethodManagerLeak(Context destContext) {
        if (destContext == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) destContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
        Field f;
        Object obj_get;
        for (String param : arr) {
            try {
                f = imm.getClass().getDeclaredField(param);
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                } // author: sodino mail:sodino@qq.com
                obj_get = f.get(imm);
                if (obj_get != null && obj_get instanceof View) {
                    View v_get = (View) obj_get;
                    if (v_get
                            .getContext() == destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                        f.set(imm, null); // 置空，破坏掉path to gc节点
                    } else {
                        // 不是想要目标销毁的，即为又进了另一层界面了，不要处理，避免影响原逻辑,也就不用继续for循环了
                        /*if (QLog.isColorLevel()) {
                            QLog.d(ReflecterHelper.class.getSimpleName(), QLog.CLR, "fixInputMethodManagerLeak break, context is not suitable, get_context=" + v_get.getContext()+" dest_context=" + destContext);
                        }*/
                        break;
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }


    //获取分辨率
    private static DisplayMetrics displayMetrics;

    /**
     * getWindowManager().getDefaultDisplay().getMetrics;
     注：构造函数DisplayMetrics 不需要传递任何参数；调用getWindowManager() 之后，
     会取得现有Activity 的Handle ，此时，getDefaultDisplay() 方法将取得的宽高维度存放于DisplayMetrics
     对象中，而取得的宽高维度是以像素为单位(Pixel) ，“像素”所指的是“绝对像素”而非“相对像素”。
     * @param context
     * @param density 传入的像素值
     * @return
     */
    public static int getDensity(Context context, int density) {
        if (displayMetrics == null) {
            displayMetrics = new DisplayMetrics();
            if (context != null)
                ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
        }
        return (int) (density * displayMetrics.density);
    }




    /**
     * 将彩色图转换为灰度图
     * @param img 位图
     * @return  返回转换好的位图
     */
    public static Bitmap convertGreyImg(Bitmap img) {
        int width = img.getWidth();         //获取位图的宽
        int height = img.getHeight();       //获取位图的高

        int []pixels = new int[width * height]; //通过位图的大小创建像素点数组

        img.getPixels(pixels, 0, width, 0, 0, width, height);
        int alpha = 0xFF << 24;
        for(int i = 0; i < height; i++)  {
            for(int j = 0; j < width; j++) {
                int grey = pixels[width * i + j];

                int red = ((grey  & 0x00FF0000 ) >> 16);
                int green = ((grey & 0x0000FF00) >> 8);
                int blue = (grey & 0x000000FF);

                grey = (int)((float) red * 0.3 + (float)green * 0.59 + (float)blue * 0.11);
                grey = alpha | (grey << 16) | (grey << 8) | grey;
                pixels[width * i + j] = grey;
            }
        }
        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        result.setPixels(pixels, 0, width, 0, 0, width, height);
        result=  MyUtils.toRoundBitmap(result);
        return result;
    }

    //bitmap变成圆形
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }
        Bitmap output = Bitmap.createBitmap(width,
                height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom);
        final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom);
        final RectF rectF = new RectF(dst);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }



}
